<template>
  <div>
    <div>
      <a-button type="primary" size="small" icon="plus" @click="addItem()">添加</a-button>
    </div>
    <a-card v-if="tempObjectList && tempObjectList.length > 0">
      <a-row>
        <a-col :span="12">
          <label for="attributeInput">变量名：</label>
        </a-col>
        <a-col :span="12">
          <label for="attributeInput">变量值：</label>
        </a-col>
      </a-row>
      <div v-if="tempObjectList.length > 0">
        <div v-for="(kv, index) in tempObjectList" :key="index">
          <a-row>
            <a-col :span="8">
              <a-input v-model="kv[0]" @change="haveChange" placeholder="请输入流程变量名" style="width: 180px"></a-input>
            </a-col>
            <a-col :span="4"></a-col>
            <a-col :span="8">
              <a-input v-model="kv[1]" @change="haveChange" placeholder="请输入流程变量值" style="width: 180px"></a-input>
            </a-col>
            <a-col :span="4">
              <div style="text-align: right">
                <a-button type="primary" size="small" icon="delete" @click="deleteIndex(index)"></a-button>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script>
import * as stream from 'stream'

export default {
  name: 'Wf_NodeBtnVariable',
  props: {
    variable: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      vObject: {},
      tempObjectList: [],
    }
  },
  methods: {
    stringToObject(ostr) {
      var replace = ostr.replace('Object(', '').replace(')', '').replace(/'/g, '"')
      return JSON.parse(replace)
    },
    objectToString(obj) {
      const ostr = JSON.stringify(obj)
      return  'Object(' + ostr + ')'
    },
    haveChange() {
      const tempObject = Object.fromEntries(this.tempObjectList)
      const newvisible = this.objectToString(tempObject)
      if (newvisible.length === 0) {
      } else {
        this.$emit('changeVariable', newvisible)
      }
    },
    addItem() {
      this.tempObjectList.push([])
    },
    deleteIndex(index) {
      this.tempObjectList.splice(index, 1)
      this.haveChange()
    },
  },
  created() {
    if (this.variable && this.variable.length > 0) {
      this.vObject = this.stringToObject(this.variable)
    }
    this.tempObjectList = Object.entries(this.vObject)
  },
}
</script>

<style scoped>
.centerBold {
  text-align: center;
  font-weight: normal;
}
</style>